﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using PracticalNEU.Models;
using SQLite;

namespace PracticalNEU.Services
{
    /// <summary>
    /// 今日天气
    /// </summary>
    public class TodayWeatherStorage : ITodayWeatherStorage
    {
        /// <summary>
        /// 数据库名。
        /// </summary>
        private const string DbName = "praticalNEUdb.db";

        /// <summary>
        /// 数据库路径。
        /// </summary>
        public static readonly string DbPath =
            Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder
                    .LocalApplicationData), DbName);

        /// <summary>
        /// 偏好存储。
        /// </summary>
        private IPreferenceStorage _preferenceStorage;

        /// <summary>
        /// 数据库版本。
        /// </summary>
        public const int Version = 1;

        /// <summary>
        /// 数据库版本键。
        /// </summary>
        public const string VersionKey = nameof(TodayWeatherStorage) + "." + nameof(Version);

        // <summary>
        /// 数据库连接影子变量。
        /// </summary>
        private SQLiteAsyncConnection _connection;

        /// <summary>
        /// 数据库连接。
        /// </summary>
        private SQLiteAsyncConnection Connection =>
            _connection ??
            (_connection = new SQLiteAsyncConnection(DbPath));

        /// <summary>
        /// 构造方法。
        /// </summary>
        /// <param name="preferenceStorage"></param>
        public TodayWeatherStorage(IPreferenceStorage preferenceStorage)
        {
            _preferenceStorage = preferenceStorage;
        }

        /// <summary>
        /// 初始化数据库。
        /// </summary>
        /// <returns></returns>
        public async Task InitializeAsync()
        {
            using (var dbFileStream = new FileStream(DbPath, FileMode.Create))
            using (var dbAssertStream = Assembly.GetExecutingAssembly()
                .GetManifestResourceStream(DbName))
                await dbAssertStream.CopyToAsync(dbFileStream);
            _preferenceStorage.Set(VersionKey, Version);
            await GetTodayWeatherFromApiAsync();
        }

        /// <summary>
        /// 是否已经初始化。
        /// </summary>
        public bool IsInitialized() =>
            _preferenceStorage.Get(VersionKey, -1) == Version;

        public async Task<int> SaveTodayWeatherInfoAsync(TodayWeather todayWeather)
        {
            var insertResult = await Connection.InsertOrReplaceAsync(todayWeather);
            return insertResult;
        }

        /// <summary>
        /// 从api保存今日天气至数据库。
        /// </summary>
        /// <returns></returns>
        public async Task GetTodayWeatherFromApiAsync()
        {
            TodayWeather todayWeather = new TodayWeather();
            HttpClient httpClient = new HttpClient();
            //httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json");
            httpClient.DefaultRequestHeaders.Add("X-Bce-Signature", "AppCode/079ab629992c424db2afd5d70cafbf3e");
            //发起请求，得到response
            var response = await httpClient.GetAsync("http://weather.api.bdymkt.com/day?cityid=101070101");
            response.EnsureSuccessStatusCode();
            //读取返回内容
            var weatherString = await response.Content.ReadAsStringAsync();
            todayWeather = JsonConvert.DeserializeObject<TodayWeather>(weatherString);
            await SaveTodayWeatherInfoAsync(todayWeather);
        }

        /// <summary>
        /// 从数据库获取今日天气。
        /// </summary>
        /// <returns></returns>
        public async Task<TodayWeather> GetTodayWeatherFromDataBaseAsync()
        {
            var todayWeather = await Connection.FindWithQueryAsync<TodayWeather>("select * from today_weather where City=?",
                "沈阳");
            return todayWeather;
        }
    }
}
